package com.zzh.netty.nettyChat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *@ClassName CatServerHandler
 *@date 2021/2/1 22:35
 *@Version 1.0
 *@Description //
 */
public class CatServerHandler extends ChannelInboundHandlerAdapter {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
    //上线发出操作
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
         Channel channel = ctx.channel();
         //将该用户加入聊天室的信息推送给其他用户
         channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"上线了"+sdf.format(new Date()));
         //将当前的channel加入group中
        channelGroup.add(channel);
        System.out.println(channel.remoteAddress()+"上线了 ");
    }

    //下线出发操作
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"下线了"+sdf.format(new Date()));
        System.out.println(channel.remoteAddress()+"下线了 ");
        System.out.println(channelGroup.size());

    }
    //读数据操作
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(i->{
            if (channel != i) {
                i.writeAndFlush("[客户端]"+channel.remoteAddress()+"发送了消息"+msg);
            } else {
                i.writeAndFlush("自己发送了"+msg);
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
